package com.xwm93up.threadsecurity;

import java.sql.SQLOutput;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description: desc
 * @Author: xwm93up
 * @Since: 2022/5/19 14:45
 */
public class ThreadLockSecurity {
    static int tickets = 10;

    class SellTickets implements Runnable{
        Lock lock = new ReentrantLock();

        @Override
        public void run() {
            while (tickets > 0) {
                try {
                    // Lock锁机制
                    lock.lock();
                    if (tickets <= 0) {
                        return;
                    }
                    System.out.println(Thread.currentThread().getName()+"--->售出第:" + tickets + "票");
                    tickets--;
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (tickets <= 0) {
                System.out.println(Thread.currentThread().getName()+"---->售票结束");
            }
        }
    }

    public static void main(String[] args) {
        SellTickets sellTickets = new ThreadLockSecurity().new SellTickets();
        Thread thread1 = new Thread(sellTickets, "1号窗口");
        Thread thread2 = new Thread(sellTickets, "2号窗口");
        Thread thread3 = new Thread(sellTickets, "3号窗口");
        Thread thread4 = new Thread(sellTickets, "4号窗口");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }
}
